/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { getUploadAuthList, addGpAuth, deleteGpAuth } from '@/services/cityXLS';
import { Button, Col, message, Popconfirm, Row } from 'antd';
import { useDebounceFn } from '@ant-design/pro-utils';
import KbPreViewPopover from '@/components/KbPreViewPopover';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { UploadAuthListItem } from './UploadAuthProps';
import styles from './HTUpload.less';

/**
 * 共配接口上传授权
 *  */
const UploadAuth: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const modalFormRef = useRef<ProFormInstance>();

  const fetchTableList = useCallback((params) => {
    const { current: page_num, ...rest } = params;
    return getUploadAuthList({
      page: page_num,
      size: 20,
      account: rest.account,
    });
  }, []);

  const onSearch = useDebounceFn(async () => {
    formRef.current?.submit();
  }, 300);

  // const exportFn = useDebounceFn(() => {
  //   const account = formRef.current?.getFieldValue('account');
  //   return gpExportExcel({ account });
  // }, 300);

  const onAdd = async (val: { account: string; phone?: string }) => {
    const { code, msg } = await addGpAuth(val);
    if (code == 0) {
      modalFormRef.current?.resetFields();
      actionRef.current?.reload();
      message.success('添加成功');
      return true;
    }
    message.error(msg);
    return false;
  };

  const onDelete = async (id: string) => {
    const { code, msg } = await deleteGpAuth({ id });
    if (code == 0) {
      message.success('删除成功');
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };

  const columns: ProColumns<UploadAuthListItem>[] = [
    {
      title: '智慧平台注册账号',
      dataIndex: 'account',
      align: 'center',
      fieldProps: {
        placeholder: '请输入智慧平台注册账号',
      },
      formItemProps: {
        label: '',
      },
      render: (_, record) => {
        const { account, id } = record;
        return (
          <KbPreViewPopover
            text={account}
            name='account'
            api='/Authorization/authorizationGetOne'
            queryData={{ id }}
          />
        );
      },
    },
    {
      title: '所属智慧平台名称',
      dataIndex: 'smartPlatformName',
      align: 'center',
      search: false,
    },
    {
      title: '申请开放平台手机号',
      dataIndex: 'kopPhone',
      align: 'center',
      search: false,
      render: (_, record) => {
        const { account, id } = record;
        return (
          <KbPreViewPopover
            text={account}
            name='account'
            api='/Authorization/authorizationGetOne'
            queryData={{ id }}
          />
        );
      },
    },
    {
      title: '申请开放平台公司名称',
      dataIndex: 'kopCompayName',
      align: 'center',
      search: false,
    },
    {
      title: '添加时间',
      dataIndex: 'create_time',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      align: 'center',
      search: false,
      render: (_, record) => {
        return (
          <Popconfirm
            title='确认删除该数据？'
            placement='topLeft'
            onConfirm={() => onDelete(record.id)}
          >
            <a>删除</a>
          </Popconfirm>
        );
      },
    },
  ];

  return (
    <PageContainer className={styles.main} title=''>
      <DragTable>
        <ProTable<UploadAuthListItem>
          className='kb-pro-table'
          formRef={formRef}
          actionRef={actionRef}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          rowKey='id'
          request={fetchTableList}
          columns={columns}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender() {
              return [
                <Row key='search'>
                  <Row justify='space-between' gutter={[20, 0]}>
                    <Col>
                      <Row gutter={[20, 0]}>
                        <Col>
                          <Button type='primary' key='submit' onClick={onSearch.run}>
                            查询
                          </Button>
                        </Col>
                      </Row>
                    </Col>
                    <Col>
                      <ModalForm
                        formRef={modalFormRef}
                        onFinish={onAdd}
                        width={600}
                        layout='horizontal'
                        title='共配接口上传授权'
                        modalProps={{
                          centered: true,
                          okText: '新增',
                        }}
                        trigger={
                          <Button type='primary' key='submit'>
                            新增
                          </Button>
                        }
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                      >
                        <ProFormText
                          width='md'
                          name='account'
                          label='智慧平台注册账号'
                          placeholder='请输入智慧平台注册账号'
                          rules={[
                            {
                              required: true,
                              message: '请输入智慧平台注册账号',
                            },
                          ]}
                        />
                        <ProFormText
                          width='md'
                          name='phone'
                          label='申请开放平台手机号'
                          placeholder='请输入设备商开放平台账号'
                          help={
                            <span style={{ color: 'red' }}>
                              如果客户使用快宝官方狂扫，则无需维护开放平台账号
                            </span>
                          }
                        />
                      </ModalForm>
                    </Col>
                  </Row>
                </Row>,
              ];
            },
          }}
          options={false}
          scroll={{ x: 1200 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default UploadAuth;
